import { defineConfig, loadEnv } from "vite";
import react from "@vitejs/plugin-react-swc";
import path from "path";
import vitePluginImp from "vite-plugin-imp";
import AutoImport from "unplugin-auto-import/vite";
import AntdResolver from "unplugin-auto-import-antd";
export default defineConfig(({ mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd());

  return {
    root: path.resolve(__dirname, "app/"),
    plugins: [
      react({
        jsxRuntime: "automatic",
        jsxImportSource: "react", // 指定 JSX 工厂函数路径
        tsDecorators: true,
        devTarget: "es2022",
      }),
      vitePluginImp({
        libList: [
          {
            libName: "antd",
            replaceOldImport: true,
            libDirectory: "es", // 确保是 'es' 而不是 'lib'
            style: (name) => `antd/es/${name}/style/index.less`, // 路径必须正确
          },
        ],
      }),
      AutoImport({
        resolvers: [AntdResolver()], // 自动导入 antd 组件
      }),
    ],

    resolve: {
      alias: {
        "@": path.resolve(__dirname, "app/src"),
      },
    },

    optimizeDeps: {
      include: [
        "react",
        "react-dom",
        "react/jsx-runtime",
        "react/jsx-dev-runtime",
        // 包含工作区包以确保预构建
        "@db-ui-simple/components",
        "@db-ui-simple/icons",
        "@db-ui-simple/utils",
      ],
      // 排除不需要预构建的包
      exclude: [],
      // ESBuild 配置用于更快的依赖预构建
      esbuildOptions: {
        target: "es2022",
        supported: {
          // 支持 React 19 的新特性
          "top-level-await": true,
        },
      },
    },
    build: {
      outDir: path.resolve(__dirname, "dist-demo"),
      emptyOutDir: true,
      // 生产环境构建优化
      target: "es2022",
      minify: "terser",
      sourcemap: mode !== "production",
      // Rollup 配置
      rollupOptions: {
        output: {
          // 手动代码分割策略
          manualChunks: {
            "react-vendor": ["react", "react-dom"],
            "ui-vendor": ["antd"],
            "utils-vendor": ["@db-ui-simple/utils"],
          },
          // 优化 chunk 命名
          chunkFileNames: "assets/[name]-[hash].js",
          entryFileNames: "assets/[name]-[hash].js",
          assetFileNames: "assets/[name]-[hash].[ext]",
        },
        external: [],
      },
      // 优化 chunk 大小警告限制
      chunkSizeWarningLimit: 1000,
    },
    server: {
      port: 10000,
      open: true,
      hmr: {
        overlay: true,
        timeout: 5000,
      },
      proxy: {
        "/tenant": {
          target: "http://192.168.10.201:20010/tenant",
          changeOrigin: true,
          ws: true,
          rewrite: (path) => path.replace(new RegExp(`^/tenant`), ""),
        },
      },
      // 允许的主机
      allowedHosts: ["localhost", "127.0.0.1"],
    },
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
          additionalData: `@import "@/config/antd.less";`, // 全局变量注入
        },
      },
      // CSS 模块化配置
      modules: {
        localsConvention: "camelCase",
        generateScopedName: "[name]__[local]___[hash:base64:5]",
      },
    },

    // 8. 环境变量配置
    define: {
      __APP_ENV__: JSON.stringify(env.NODE_ENV || "development"),
      // 支持 React 19 的全局变量
      "process.env.NODE_ENV": JSON.stringify(mode),
    },
  };
});
